package net.liuyimin.service;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class StockService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private ReentrantLock reentrantLock = new ReentrantLock();

    /**
     * 演示共享资源在Redis中在高并发下的超卖问题
     */
    public void deduct() {
        // 1.查询库存信息
        String stock = this.stringRedisTemplate.opsForValue().get("stock");

        // 2.判断库存是否充足
        if (stock != null && stock.length() != 0) {
            Integer st = Integer.valueOf(stock);
            if (st > 0) {
                // 3.扣减库存
                this.stringRedisTemplate.opsForValue().set("stock", String.valueOf(st - 1));
            }
        }
    }

    /**
     * JVM本地锁 : 使用ReentrantLock可重入锁解决超卖现象
     */
    public void deductByReentrantLock() {
        reentrantLock.lock();
        try {
            // 1.查询库存信息
            String stock = this.stringRedisTemplate.opsForValue().get("stock");

            // 2.判断库存是否充足
            if (stock != null && stock.length() != 0) {
                Integer st = Integer.valueOf(stock);
                if (st > 0) {
                    // 3.扣减库存
                    this.stringRedisTemplate.opsForValue().set("stock", String.valueOf(st - 1));
                }
            }
        } finally {
            reentrantLock.unlock();
        }
    }

    /**
     * Redis乐观锁 : 使用Redis事务解决超卖现象
     */
    public void deductByWatchMultiExec() {
        // 借助execute方法实现Redis事务
        this.stringRedisTemplate.execute(new SessionCallback<Object>() {
            // RedisOperations 本质就是 RedisTemplate 及 StringRedisTemplate
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                // watch
                operations.watch("stock");

                // 1.查询库存信息
                String stock = operations.opsForValue().get("stock").toString();

                // 2.判断库存是否充足
                int st = 0;
                if (stock != null && (st = Integer.parseInt(stock.toString())) > 0) {
                    st = Integer.valueOf(stock);
                    if (st > 0) {
                        // multi
                        operations.multi();

                        // 3.扣减库存
                        operations.opsForValue().set("stock", String.valueOf(--st));

                        // exec
                        List exec = operations.exec();
                        // 如果执行事务的返回结果集为空，则代表减库存失败，进行重试
                        // 如果exec为空，说明事务没有执行,说明在watch之后，key发生了变化，需要重新执行方法
                        if (exec == null || exec.size() == 0) {
                            try {
                                // 睡眠时间取决于电脑性能，但是在高并发下可能还是会出现问题
                                TimeUnit.SECONDS.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            deduct();
                        }
                        return exec;
                    }
                }
                return null;
            }
        });
    }

}
